<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="创建字典12345678vegetables &#x3D; [(&amp;#x27;celery&amp;#x27;, 1.58), (&amp;#x27;brocoli&amp;#x27;, 1.29), (&amp;#x27;lettuce&amp;#x27;, 2.19)]# 创建包含3组key-value对的字典dict3 &#x3D; dict(vegetables)print(dict3) # &amp;#123;&amp;#x27;celery&amp;#x27;: 1.5">
<meta property="og:type" content="article">
<meta property="og:title" content="python operation of dict">
<meta property="og:url" content="https://bgape002.gitee.io/2021/03/24/python-operation-of-dict/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="创建字典12345678vegetables &#x3D; [(&amp;#x27;celery&amp;#x27;, 1.58), (&amp;#x27;brocoli&amp;#x27;, 1.29), (&amp;#x27;lettuce&amp;#x27;, 2.19)]# 创建包含3组key-value对的字典dict3 &#x3D; dict(vegetables)print(dict3) # &amp;#123;&amp;#x27;celery&amp;#x27;: 1.5">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-03-24T09:21:46.000Z">
<meta property="article:modified_time" content="2022-01-27T02:24:05.809Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="dict">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bgape002.gitee.io/2021/03/24/python-operation-of-dict/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>python operation of dict | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2021/03/24/python-operation-of-dict/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python operation of dict
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-03-24 17:21:46" itemprop="dateCreated datePublished" datetime="2021-03-24T17:21:46+08:00">2021-03-24</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2022-01-27 10:24:05" itemprop="dateModified" datetime="2022-01-27T10:24:05+08:00">2022-01-27</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2021/03/24/python-operation-of-dict/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2021/03/24/python-operation-of-dict/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="创建字典"><a href="#创建字典" class="headerlink" title="创建字典"></a>创建字典</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">vegetables = [(<span class="string">&#x27;celery&#x27;</span>, <span class="number">1.58</span>), (<span class="string">&#x27;brocoli&#x27;</span>, <span class="number">1.29</span>), (<span class="string">&#x27;lettuce&#x27;</span>, <span class="number">2.19</span>)]</span><br><span class="line"><span class="comment"># 创建包含3组key-value对的字典</span></span><br><span class="line">dict3 = <span class="built_in">dict</span>(vegetables)</span><br><span class="line"><span class="built_in">print</span>(dict3) <span class="comment"># &#123;&#x27;celery&#x27;: 1.58, &#x27;brocoli&#x27;: 1.29, &#x27;lettuce&#x27;: 2.19&#125;</span></span><br><span class="line">cars = [[<span class="string">&#x27;BMW&#x27;</span>, <span class="number">8.5</span>], [<span class="string">&#x27;BENS&#x27;</span>, <span class="number">8.3</span>], [<span class="string">&#x27;AUDI&#x27;</span>, <span class="number">7.9</span>]]</span><br><span class="line"><span class="comment"># 创建包含3组key-value对的字典</span></span><br><span class="line">dict4 = <span class="built_in">dict</span>(cars)</span><br><span class="line"><span class="built_in">print</span>(dict4) <span class="comment"># &#123;&#x27;BMW&#x27;: 8.5, &#x27;BENS&#x27;: 8.3, &#x27;AUDI&#x27;: 7.9&#125;</span></span><br></pre></td></tr></table></figure>

<p><strong>字典中重复键</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">vegetables = [(<span class="string">&#x27;celery&#x27;</span>, <span class="number">1.58</span>), (<span class="string">&#x27;brocoli&#x27;</span>, <span class="number">1.29</span>), (<span class="string">&#x27;lettuce&#x27;</span>, <span class="number">2.19</span>), (<span class="string">&#x27;brocoli&#x27;</span>, <span class="number">2.29</span>), (<span class="string">&#x27;lettuce&#x27;</span>, <span class="number">3.19</span>)]</span><br><span class="line">dict3 = <span class="built_in">dict</span>(vegetables)</span><br><span class="line"><span class="built_in">print</span>(dict3)   <span class="comment"># &#123;&#x27;celery&#x27;: 1.58, &#x27;brocoli&#x27;: 2.29, &#x27;lettuce&#x27;: 3.19&#125;</span></span><br></pre></td></tr></table></figure>

<span id="more"></span>

<h3 id="字典：查"><a href="#字典：查" class="headerlink" title="字典：查"></a>字典：查</h3><p><strong>直接获取值</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line">cars[<span class="string">&#x27;BMW&#x27;</span>]   <span class="comment"># 8.5</span></span><br></pre></td></tr></table></figure>

<p><strong>get方法获取值</strong></p>
<p>get方法获取，可以避免键不存在报错情况</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">dict</span>.get(key, default=<span class="literal">None</span>)</span><br><span class="line"><span class="comment"># key – 字典中要查找的键。</span></span><br><span class="line"><span class="comment"># default – 如果指定键的值不存在时，返回该默认值。</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line"><span class="comment"># 获取&#x27;BMW&#x27;对应的value</span></span><br><span class="line"><span class="built_in">print</span>(cars.get(<span class="string">&#x27;BMW&#x27;</span>)) <span class="comment"># 8.5</span></span><br><span class="line"><span class="built_in">print</span>(cars.get(<span class="string">&#x27;PORSCHE&#x27;</span>)) <span class="comment"># None</span></span><br><span class="line"><span class="built_in">print</span>(cars[<span class="string">&#x27;PORSCHE&#x27;</span>]) <span class="comment"># KeyError: &#x27;PORSCHE&#x27;</span></span><br></pre></td></tr></table></figure>

<h3 id="setdefault-方法"><a href="#setdefault-方法" class="headerlink" title="setdefault()方法"></a>setdefault()方法</h3><blockquote>
<p><strong>setdefault() 方法也用于根据 key 来获取对应 value 的值。</strong><br>但该方法有一个额外的功能，即当程序要获取的 key 在字典中不存在时，该方法会先为这个不存在的 key 设置一个默认的 value，然后再返回该 key 对应的 value。<br>总之，setdefault() 方法总能返回指定 key 对应的 value；<br>如果该 key-value 对存在，则直接返回该 key 对应的 value；如果该 key-value 对不存在，则先为该 key 设置默认的 value，然后再返回该 key 对应的 value。</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line"><span class="comment"># 设置默认值，该key在dict中不存在，新增key-value对</span></span><br><span class="line"><span class="built_in">print</span>(cars.setdefault(<span class="string">&#x27;PORSCHE&#x27;</span>, <span class="number">9.2</span>)) <span class="comment"># 9.2</span></span><br><span class="line"><span class="built_in">print</span>(cars)   <span class="comment"># &#123;&#x27;BMW&#x27;: 8.5, &#x27;BENS&#x27;: 8.3, &#x27;AUDI&#x27;: 7.9, &#x27;PORSCHE&#x27;: 9.2&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置默认值，该key在dict中存在，不会修改dict内容</span></span><br><span class="line"><span class="built_in">print</span>(cars.setdefault(<span class="string">&#x27;BMW&#x27;</span>, <span class="number">3.4</span>)) <span class="comment"># 8.5</span></span><br><span class="line"><span class="built_in">print</span>(cars)  <span class="comment"># &#123;&#x27;BMW&#x27;: 8.5, &#x27;BENS&#x27;: 8.3, &#x27;AUDI&#x27;: 7.9, &#x27;PORSCHE&#x27;: 9.2&#125;</span></span><br></pre></td></tr></table></figure>



<h3 id="字典：增、改"><a href="#字典：增、改" class="headerlink" title="字典：增、改"></a>字典：增、改</h3><p><strong>直接键操作</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line">cars[<span class="string">&#x27;BMW&#x27;</span>] = <span class="number">5</span></span><br><span class="line">cars[<span class="string">&#x27;PORSCHE&#x27;</span>] = <span class="number">9</span></span><br><span class="line"><span class="built_in">print</span>(cars)      <span class="comment"># &#123;&#x27;BMW&#x27;: 5, &#x27;BENS&#x27;: 8.3, &#x27;AUDI&#x27;: 7.9, &#x27;PORSCHE&#x27;: 9&#125;</span></span><br></pre></td></tr></table></figure>

<p><strong>update方法</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line">cars.update(&#123;<span class="string">&#x27;BMW&#x27;</span>:<span class="number">4.5</span>, <span class="string">&#x27;PORSCHE&#x27;</span>: <span class="number">9.3</span>&#125;)</span><br><span class="line"><span class="built_in">print</span>(cars)    <span class="comment"># &#123;&#x27;BMW&#x27;: 4.5, &#x27;BENS&#x27;: 8.3, &#x27;AUDI&#x27;: 7.9, &#x27;PORSCHE&#x27;: 9.3&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="字典：删"><a href="#字典：删" class="headerlink" title="字典：删"></a>字典：删</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(cars.pop(<span class="string">&#x27;AUDI&#x27;</span>))   <span class="comment"># 7.9</span></span><br><span class="line"><span class="built_in">print</span>(cars)   <span class="comment"># &#123;&#x27;BMW&#x27;: 8.5, &#x27;BENS&#x27;: 8.3&#125;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">popitem()方法: popitem() 方法用于随机弹出字典中的一个 key-value 对。</span></span><br><span class="line"><span class="string">此处的随机其实是假的，正如列表的 pop() 方法总是弹出列表中最后一个元素，实际上字典的 popitem() 其实也是弹出字典中最后一个 key-value 对。</span></span><br><span class="line"><span class="string">由于字典存储 key-value 对的顺序是不可知的，</span></span><br><span class="line"><span class="string">因此开发者感觉字典的 popitem() 方法是“随机”弹出的，但实际上字典的 popitem() 方法总是弹出底层存储的最后一个 key-value 对。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line">cars = &#123;<span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>&#125;</span><br><span class="line"><span class="built_in">print</span>(cars)</span><br><span class="line"><span class="comment"># 弹出字典底层存储的最后一个key-value对</span></span><br><span class="line"><span class="built_in">print</span>(cars.popitem()) <span class="comment"># (&#x27;AUDI&#x27;, 7.9)</span></span><br><span class="line"><span class="built_in">print</span>(cars) <span class="comment"># &#123;&#x27;BMW&#x27;: 8.5, &#x27;BENS&#x27;: 8.3&#125;</span></span><br></pre></td></tr></table></figure>

<p>实际上 <code>popitem</code> 弹出的就是一个元组，因此程序完全可以通过序列解包的方式用两个变量分别接收 <code>key</code> 和 <code>value</code>。将弹出项的<code>key</code>赋值给<code>k</code>、<code>value</code>赋值给<code>v</code></p>
<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">k, v = cars.popitem()</span><br><span class="line"><span class="built_in">print</span>(k, v) <span class="comment"># BENS 8.3</span></span><br></pre></td></tr></table></figure>

<h3 id="获取字典键值对"><a href="#获取字典键值对" class="headerlink" title="获取字典键值对"></a>获取字典键值对</h3><blockquote>
<p><strong>items()、keys()、values() 分别用于获取字典中的所有 key-value 对、所有 key、所有 value。</strong><br>这三个方法依次返回 dict_items、dict_keys 和 dict_values 对象，Python 不希望用户直接操作这几个方法，但可通过 list() 函数把它们转换成列表。<br>如下代码示范了这三个方法的用法：</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">cars = &#123;<span class="string">&#x27;BMW&#x27;</span>: <span class="number">8.5</span>, <span class="string">&#x27;BENS&#x27;</span>: <span class="number">8.3</span>, <span class="string">&#x27;AUDI&#x27;</span>: <span class="number">7.9</span>&#125;</span><br><span class="line"><span class="comment"># 获取字典所有的key-value对，返回一个dict_items对象</span></span><br><span class="line">ims = cars.items()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(ims)) <span class="comment"># &lt;class &#x27;dict_items&#x27;&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 将dict_items转换成列表</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(ims)) <span class="comment"># [(&#x27;BMW&#x27;, 8.5), (&#x27;BENS&#x27;, 8.3), (&#x27;AUDI&#x27;, 7.9)]</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 访问第2个key-value对</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(ims)[<span class="number">1</span>]) <span class="comment"># (&#x27;BENS&#x27;, 8.3)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取字典所有的key，返回一个dict_keys对象</span></span><br><span class="line">kys = cars.keys()</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(kys)) <span class="comment"># &lt;class &#x27;dict_keys&#x27;&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 将dict_keys转换成列表</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(kys)) <span class="comment"># [&#x27;BMW&#x27;, &#x27;BENS&#x27;, &#x27;AUDI&#x27;]</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 访问第2个key</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(kys)[<span class="number">1</span>]) <span class="comment"># &#x27;BENS&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取字典所有的value，返回一个dict_values对象</span></span><br><span class="line">vals = cars.values()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 将dict_values转换成列表</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">type</span>(vals)) <span class="comment"># [8.5, 8.3, 7.9]</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 访问第2个value</span></span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">list</span>(vals)[<span class="number">1</span>]) <span class="comment"># 8.3</span></span><br></pre></td></tr></table></figure>

<h3 id="字典格式化字符串"><a href="#字典格式化字符串" class="headerlink" title="字典格式化字符串"></a>字典格式化字符串</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 字符串模板中使用key</span></span><br><span class="line">temp = <span class="string">&#x27;教程是:%(name)s, 价格是:%(price)010.2f&#x27;</span></span><br><span class="line">book = &#123;<span class="string">&#x27;name&#x27;</span>:<span class="string">&#x27;Python基础教程&#x27;</span>, <span class="string">&#x27;price&#x27;</span>: <span class="number">99</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用字典为字符串模板中的key传入值</span></span><br><span class="line"><span class="built_in">print</span>(temp % book)   <span class="comment"># 教程是:Python基础教程, 价格是:0000099.00</span></span><br></pre></td></tr></table></figure>


    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/dict/" rel="tag"><i class="fa fa-tag"></i> dict</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2021/03/24/H5%E6%A0%87%E7%AD%BE/" rel="prev" title="H5标签">
      <i class="fa fa-chevron-left"></i> H5标签
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2021/03/25/recursive-algorithm/" rel="next" title="recursive algorithm">
      recursive algorithm <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E5%AD%97%E5%85%B8"><span class="nav-number">1.</span> <span class="nav-text">创建字典</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E5%85%B8%EF%BC%9A%E6%9F%A5"><span class="nav-number">2.</span> <span class="nav-text">字典：查</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#setdefault-%E6%96%B9%E6%B3%95"><span class="nav-number">3.</span> <span class="nav-text">setdefault()方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E5%85%B8%EF%BC%9A%E5%A2%9E%E3%80%81%E6%94%B9"><span class="nav-number">4.</span> <span class="nav-text">字典：增、改</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E5%85%B8%EF%BC%9A%E5%88%A0"><span class="nav-number">5.</span> <span class="nav-text">字典：删</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96%E5%AD%97%E5%85%B8%E9%94%AE%E5%80%BC%E5%AF%B9"><span class="nav-number">6.</span> <span class="nav-text">获取字典键值对</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E5%85%B8%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-number">7.</span> <span class="nav-text">字典格式化字符串</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
